import React, {useState} from "react";
import './style.css';
import axios from "axios";
import {toast} from "react-toastify";

export default function FileUpLoader({onSuccess}) {
    const [file, setFile] = useState([]);
    const onInputChange = (e) => {
        //e.target.value 只是文件的路径
        console.log(e.target.files);
        setFile(e.target.files);
        // setFile(e.target.files[0]);
    }
    const onSubmit = (e) => {
        e.preventDefault();
        const data = new FormData();
        //data.append('file',file);
        for (let i = 0; i < file.length; i++) {
            console.log(file[i]);
            data.append('file', file[i]);
        }
        axios.post('http://localhost:8000/upload', data).then((response) => {
            // console.log('Success');
            toast.success('Upload success');
            onSuccess(response.data);
        })
            .catch((e) => {
                toast.error('Upload Error', e);
            })
    }
    return (
        <React.Fragment>
            <form
                method={'post'}
                action="src/components/FileUploader/FileUpLoader#" id={"#"}
                onSubmit={onSubmit}
            >
                <div className={"form-group files"}>
                    <label>
                        上传文件
                    </label>
                    <input
                        onChange={onInputChange}
                        type="file"
                        className={"form-control"}
                        multiple
                    />
                </div>
                <button>提交</button>
            </form>
        </React.Fragment>
    )
}